package com.health.tools;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.health.NovaApplication;
import com.health.activity.settings.DataDownLoadMainActivity;
import com.health.activity.settings.Manager;
import com.health.tablebean.JTYS_SignPictureData;
import com.novabluetooth.services.ktxyj.Constants;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import static com.health.tools.GlobalConts.UPLOAD_TYPE;

/**
 * WebService数据上传类
 */
public class UploadDatas {
    private final static int INIT = -1;
    private Context context;
    private ResultTextDialog resultDialog;
    private int dataCount = INIT;
    private UploadDataBean[] dataBeans;
    private int j = 0;
    private int k = 0;
    int s = 0;
    int f = 0;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    j++;
                    break;
                case 1:
                    k++;
                    break;
            }
            return true;
        }
    });

    /**
     * 数据上传类
     *
     * @param context   Activity
     * @param dataBeans
     */
    public UploadDatas(Context context, UploadDataBean... dataBeans) {
        this.context = context;
        this.dataBeans = dataBeans;
        dataCount = INIT;
    }

    /**
     * 数据上传类
     *
     * @param context   Activity
     * @param dataBeans
     */
    public UploadDatas(Context context, List<UploadDataBean> dataBeans) {
        this.context = context;
        DataDownLoadMainActivity cs = (DataDownLoadMainActivity) context;
        cs.getHandler();
        if (dataBeans != null) {
            int size = dataBeans.size();
            this.dataBeans = new UploadDataBean[size];
            this.dataBeans = dataBeans.toArray(this.dataBeans);
        }

        dataCount = INIT;
    }

    /**
     * 开始上传数据
     *
     * @author 鹿云龙
     * @date 2017年12月18日 下午1:48:38
     */
    public void uploadDatas() {
        dataCount = INIT;
        if (resultDialog == null) {
            resultDialog = new ResultTextDialog(context);
        } else {

        }


//        resultDialog.show("数据正在上传中，请稍候...");
        log("开始上传数据");
        if (dataBeans != null && dataBeans.length > 0) {
            uploadData();
        } else {
            log("+++++++++++++++++");
            setDialogText("暂无数据上传！");
            resultDialog.showCancleLong();

        }
    }

    // 递归调用下载所有数据
    private void uploadData() {
        if (dataCount != INIT) {
            wait(2000);
        }
        dataCount += 1;
        Log.e("eeeeeeeeeeeeee", dataBeans.length + "");
        if (dataCount == dataBeans.length) {
            // 上传结束
            log("上传结束");
            dataCount = INIT;
            setDialogText("数据上传完成！");
            resultDialog.showCancleLong();
//            Toast.makeText(context, "数据上传完成", Toast.LENGTH_LONG).show();
            return;
        }
        final UploadDataBean data = dataBeans[dataCount];
//      setDialogText(data.getDataName() + "数据正在上传中，请稍候...");
        // 显示正在上传Dialog 1000ms
        wait(1000);

        if (dataCount < dataBeans.length) {

            //上传照片
            if ("照片".equals(data.getDataName())) {
                try {
                    final List<Object> datas = data.getDatas();
                    for (int i = 0; i < datas.size(); i++) {
                        JTYS_SignPictureData picture = (JTYS_SignPictureData) datas.get(i);
                        String fileURL = picture.getPhotoPath();
                        String fileName = picture.getPhotoName();
                        String cardNum = picture.getCardNum();
                        String type = picture.getRes0();
                        String uuid = picture.getRes1();

                        new WebService(context) {

                            public void complete(final String message) {
                                try {
                                    JSONObject obj = new JSONObject(message);
                                    String state = obj.getString("state");
                                    if (state.equals("000")) {
                                        List<JTYS_SignPictureData> pictureDatas = NovaApplication.fdbmanger
                                                .findAllByWhere(JTYS_SignPictureData.class, "photoName ='" + obj.getString("fileName") + "'");
                                        if (pictureDatas.size() > 0) {
                                            JTYS_SignPictureData pictureData = pictureDatas.get(0);
//                                            pictureData.setIsUpdate("N");
                                            NovaApplication.fdbmanger.updata(pictureData, "photoName ='" + obj.getString("fileName") + "'");
                                            Message message1 = handler.obtainMessage();
                                            message1.what = 0;
                                            handler.sendMessage(message1);

                                            if (j + k == datas.size()) {
                                                setDialogText(data.getDataName() + "数据上传成功" + j + "条\n" + k + "条数据未上传");
                                            }
                                        }
                                    } else {
                                        Message message1 = handler.obtainMessage();
                                        message1.what = 1;
                                        handler.sendMessage(message1);

                                        if (j + k == datas.size()) {
                                            setDialogText(data.getDataName() + "数据上传成功" + j + "条\n" + k + "条数据未上传");
                                        }
                                    }
                                } catch (JSONException e) {
                                    Message message1 = handler.obtainMessage();
                                    message1.what = 1;
                                    handler.sendMessage(message1);

                                    if (j + k == datas.size()) {
                                        setDialogText(data.getDataName() + "数据上传成功" + j + "条\n" + k + "条数据未上传");
                                    }
                                    e.printStackTrace();
                                }

                            }

                            public void onError(String message) {
                                Message message1 = handler.obtainMessage();
                                message1.what = 1;
                                handler.sendMessage(message1);

                                if (j + k == datas.size()) {
                                    setDialogText(data.getDataName() + "数据上传成功" + j + "条\n" + k + "条数据未上传");
                                }
                            }


                        }.uploadFile(data.getMethod(), fileURL, fileName, data.getModule(), cardNum, type, uuid);
                    }
                    wait(2000);
                    uploadData();
                } catch (Exception e) {
                    e.printStackTrace();
                    setDialogText(data.getDataName() + "数据上传失败!");
                    uploadData();
                }
            } else {
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            //用HttpClient发送请求，分为五步
                            //第一步：创建HttpClient对象
                            HttpClient httpCient = new DefaultHttpClient();
                            //第二步：创建代表请求的对象,参数是访问的服务器地址
                            HttpPost httpPost = new HttpPost(GlobalConts.URL_UPLOAD_DATA+UPLOAD_TYPE);

                            Gson gson = new Gson();
                            String str = gson.toJson(dataBeans[0],UploadDataBean.class);
                            StringEntity stringEntity = null;
                            try {
                                stringEntity = new StringEntity(str);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            stringEntity.setContentType("application/x-www-form-urlencoded");
                            httpPost.setEntity(stringEntity);
                            try {
                                //第三步：执行请求，获取服务器发还的相应对象
                                HttpResponse httpResponse = httpCient.execute(httpPost);
                                //第四步：检查相应的状态是否正常：检查状态码的值是200表示正常
                                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                                    //第五步：从相应对象当中取出数据，放到entity当中
                                    HttpEntity entity = httpResponse.getEntity();
                                    String response = EntityUtils.toString(entity, "utf-8");//将entity当中的数据转换为字符串

                                    //在子线程中将Message对象发出去
                                    if (response != null) {
                                        final int[] jx_data = JX_UploadData.jx_data(response, data.getDataType());
                                        s = jx_data[0];
                                        f = jx_data[1];
                                        Message ms = new Message();
                                        Bundle bundle = new Bundle();
                                        bundle.putString("count", s + "/" + f + "/" + data.getDataName());
                                        ms.setData(bundle);//bundle传值，耗时，效率低
                                        ms.what = 11;
                                        Manager.getInstance().sendCountMessage(ms);
                                    }
                                }else{
                                    setDialogText(data.getDataName() + "数据上传失败!");
//                                    uploadData();
                                }

                            } catch (Exception e) {
                                setDialogText(data.getDataName() + "数据上传失败!");
//                                uploadData();
                            }

                        }
                    }).start();

                }

                /*try {
                    String ss = data.getDataJsonName();
                    final List<Object> datas = data.getDatas();
                    HashMap<String, Object> uploadParams = new HashMap<String, Object>();
                    uploadParams.put(data.getDataJsonName(), new GsonBuilder().create().toJson(data.getDatas()));
                    Log.e("转换数据：", ss + "***********" + new GsonBuilder().create().toJson(data.getDatas()).toString());
                    new WebService(context) {
                        public void complete(final String message) {

//                            Manager.getInstance().sendSuccessMessage();
                            log("上传返回数据：" + message);
                            if (!("[]".equals(message))) {
                                final int[] jx_data = JX_UploadData.jx_data(message, data.getDataType());
                                s = jx_data[0];
                                f = jx_data[1];
                                Message ms = new Message();
                                Bundle bundle = new Bundle();
                                bundle.putString("count", s + "/" + f + "/" + data.getDataName());
                                ms.setData(bundle);//bundle传值，耗时，效率低
                                ms.what = 11;
                                Manager.getInstance().sendCountMessage(ms);
//                                setDialogText(data.getDataName() + "数据上传成功" + jx_data[0] + "条\n" + jx_data[1] + "条数据未上传");
                            } else {
//                                setDialogText(data.getDataName() + "无可上传数据!");
                            }
//                            uploadData();
                        }

                        public void onError(String message) {
                            setDialogText(data.getDataName() + "数据上传失败!");
                            uploadData();
                        }
                    }.uploaddata(data.getMethod(), uploadParams, data.getModule());
                } catch (Exception e) {
                    e.printStackTrace();
                    setDialogText(data.getDataName() + "数据上传失败!");
                    uploadData();
                }
            }*/

        }

    }

    private void setDialogText(final String str) {
        ((Activity) context).runOnUiThread(new Runnable() {
            public void run() {
                resultDialog.setText(str);
            }
        });
    }

    private void wait(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }

    private void log(String msg) {
        Log.i("tag", "[UploadDatas]" + msg);
    }
}